package com.fengye.serialization.serializer.impl;

import com.fengye.serialization.serializer.Serializer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.Dom4JDriver;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * @Author fengye
 * @Date 2023/2/13 10:14
 **/
public class XmlSerializer implements Serializer {

    private static final XStream xStream = new XStream(new DomDriver());

    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        if(obj ==  null) {
            return new byte[0];
        }
        return xStream.toXML(obj).getBytes();
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if(data == null) {
            return null;
        }
        String xml = new String(data);
        return (T) xStream.fromXML(xml);
    }
}
